﻿var regFlag = 0;
var VibrateFlag = "";
var mailFlag = 0;
var mail2Flag = 0;
var passwordFlag = 0;
var password2Flag = 0;
var nameFlag = 0;
var w=screen.width;
var h=screen.height;
$(document).ready(function () {
    HideAll();
    EventHandlers();
    $.post("UI/AjaxController.ashx", {
        WIDTH: w,
        HIEGHT: h,
        ACTION: "SIZE",
        ACTIONTYPE: "LOGIN"
    }, function (result) {

    });
});
function EventHandlers() {

    $("#email").blur(EmailValidator);
    $("#password").blur(PasswordValidator);
    $("#passwordConfirm").blur(PasswordConfirmValidator);
    $("#name").blur(NameValidator);
    $("#signUpButton").click(SignUpClick);
    $("#loginBottmlink").click(LoginClick);
    $("#login").click(Login);
    $("#register").click(FinalValidator);
    $('.ActionButton').click(VibrateAction);

    $("#password").keyup(PasswordValidator);
    $("#passwordConfirm").keyup(PasswordConfirmValidator);
    $("#name").keyup(NameValidator);
    $("#signUpButton").keyup(SignUpClick);
    $("#loginBottmlink").keyup(LoginClick);

    //-------------




}

//------------ Form Validation ------------//  

function EmailValidator(f) {
    if (regFlag) {
        mailFlag = 0;
        emailAddress = $("#email").val();
        if (emailAddress != "" || f == 12) {
            var regex = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
            if (regex.test(emailAddress)) {
                $("#email").removeClass("NotVarified");
                $("#Error0").hide(10);
                if (f != 12)
                    CheckMAilAvailability();
                mailFlag = 1;
                return true;
            }
            else {
                $("#email").removeClass("Varified");
                $("#email").addClass("NotVarified");
                $("#Error0").show(100);
                $("#emailError").text("Please enter a valid email address");
                return false;
            }
        }
    }
    else {
        return false;
    }
}

function PasswordValidator(f) {
    passwordFlag = 0;
    if (regFlag) {
        PasswordConfirmValidator();
        if ($("#password").val() != "" || f == 12) {
            var l = $("#password").val().length;
            if (l < 6) {
                $("#password").addClass("NotVarified");
                $("#password").removeClass("Varified");
                $("#Error1").show(100);
                $("#passwordError").text("Password too short");
                return false;
            }
            else {
                $("#password").removeClass("NotVarified");
                $("#password").addClass("Varified");
                $("#Error1").hide(10);
                passwordFlag = 1;
                return true;
            }
        }
        else {
            return false;
        }
    }
}

function PasswordConfirmValidator(f) {
    if (regFlag) {
        password2Flag = 0;
        var password1 = $("#password").val();
        var password2 = $("#passwordConfirm").val();
        if ((password1 != "" && password2 != "") || f == 12) {
            if ((password1 === password2) && password2 != "") {
                $("#passwordConfirm").addClass("Varified");
                $("#passwordConfirm").removeClass("NotVarified");
                $("#Error2").hide();
                password2Flag = 1;
                return true;
            }
            else
                if (password2 == "") {
                    $("#passwordConfirm").addClass("NotVarified");
                    $("#passwordConfirm").removeClass("Varified");
                    $("#Error2").show(100);
                    $("#passwordConfirmError").text("You must enter a password");

                }
                else {
                    $("#passwordConfirm").addClass("NotVarified");
                    $("#passwordConfirm").removeClass("Varified");
                    $("#Error2").show(100);
                    $("#passwordConfirmError").text("Passwords do not match");
                    return false;
                }
        }
        else {
            return false;
        }
    }
}

function NameValidator(f) {
    if (regFlag) {
        nameFlag = 0;
        if ($("#name").val() != "" || f == 12) {
            var l = $("#name").val().length;
            if (l < 2) {
                $("#name").addClass("NotVarified");
                $("#name").removeClass("Varified");
                $("#Error3").show(100);
                $("#nameError").text("Please Enter a valid name");
                return false;
            }
            else {
                $("#name").removeClass("NotVarified");
                $("#name").addClass("Varified");
                $("#Error3").hide(10);
                nameFlag = 1;
                return true;
            }
        }
        else {
            return false;
        }
    }
}

function CheckMAilAvailability() {

    var user = $('#email').val();
    var flag = false;
    mail2Flag = 0
    $("#timer").show(500);
    $.post("UI/AjaxController.ashx", {
        EMAIL: user,
        ACTION: "EMAILVARIFY",
        ACTIONTYPE: "LOGIN"
    }, function (result) {
        $("#timer").hide(500);
        // alert("Ajax Start");
        if (result == 1) {
            $("#email").addClass("Varified");
            $("#email").removeClass("NotVarified");
            $("#Error0").hide(10);
            flag = true;
            mail2Flag = 1;
        }
        else {
            $("#email").addClass("NotVarified");
            $("#email").removeClass("Varified");
            $("#Error0").show(100);
            $("#emailError").text("This email was submited before");
            flag = false;
        }
        return flag;
    });
    //alert(flag);

}

//----------------------------------------------End-----------------------------------//

function HideAll() {
    $("#validate").hide(0);
    $("#forgetForm").hide(0);
    $("#registerForm").hide(0);
    $("#timer").hide(0);
    $("#sendDataTimer").hide(0);
    $("#loginBottmlink").hide(0);
    $("#registerButton").hide(0);
    $(".Error").hide(0);

}

function SignUpClick() {
    regFlag = 1;
    $("#registerForm").show(1000);
    $("#loginButton").hide(5);
    $("#signupLink").hide(1000);
    $("#registerButton").show(200);
    $("#loginBottmlink").show(1000);
    $("input[type=text]").removeClass("Varified");
    $("input[type=text]").removeClass("NotVarified");
    $("input[type=password]").removeClass("Varified");
    $("input[type=password]").removeClass("NotVarified");
    $(".ForgetPassword").hide(0);
    $(".Error").hide(0);
}

function LoginClick() {
    regFlag = 0;
    $("#registerForm").hide(1000);
    $("#loginButton").show(5);
    $("#signupLink").show(1000);
    $("#registerButton").hide(200);
    $("#loginBottmlink").hide(1000);
    $("input[type=text]").removeClass("Varified");
    $("input[type=text]").removeClass("NotVarified");
    $("input[type=password]").removeClass("Varified");
    $("input[type=password]").removeClass("NotVarified");
    $(".ForgetPassword").show(0);
    $(".Error").hide(0);
}

function Login() {

    $("#password").removeClass("NotVarified");
    $("#email").removeClass("NotVarified");
    $("#Error1").hide(0);
    $("#Error0").hide(0);
    $("#login").unbind();
    var user = $('#email').val();
    var password = $("#password").val();
    $("#sendDataTimer").show(500);
    $.post("UI/AjaxController.ashx", {
        EMAIL: user,
        PASSWORD: password,
        ACTION: "LOGIN",
        ACTIONTYPE: "LOGIN"
    }, function (result) {
        $("#sendDataTimer").hide(500);
        if (result == 1) {

            $("#password").addClass("NotVarified");
            $("#password").addClass("NotVarified");
            $("#Error1").show(100);
            $("#passwordError").text("Wrong password");
            VibrateAction();
            flag = false;

        }
        else
            if (result == 2) {

                $("#email").addClass("NotVarified");
                $("#Error0").show(100);
                $("#emailError").text("This email does not exist in our database");
                VibrateAction();
                flag = false;
            }

            else
                if (result == 0) {

                    window.location.replace("/UI/Desktop.aspx");

                }
    });
    $("#login").click(Login);
}

function FinalValidator() {
    if (mailFlag + mail2Flag + password2Flag + passwordFlag + nameFlag == 5) {
        Register()
    }
    else {
        if (mailFlag == 0) {

            EmailValidator();
        }
        if (mail2Flag == 0) {

            CheckMAilAvailability();
        }
        if (passwordFlag == 0) {

            PasswordValidator();
        }
        if (password2Flag == 0) {
            PasswordConfirmValidator();
        }
        if (nameFlag == 0) {
            NameValidator();
        }
        if (mailFlag + mail2Flag + password2Flag + passwordFlag + nameFlag == 5) {
            FinalValidator();
            FinalValidator();
            VibrateAction();
        }
    }


}

function Register() {

    $("#register").hide(0);
    var user = $('#email').val();
    var password = $("#password").val();
    var name = $("#name").val();
    $("#sendDataTimer").show(500);
    $.post("UI/AjaxController.ashx", {
        EMAIL: user,
        PASSWORD: password,
        NAME: name,
        ACTION: "REGISTER",
        ACTIONTYPE: "LOGIN"
    }, function (result) {
        $("#sendDataTimer").hide(500);
        if (result == 1) {

            //alert("Some Un handle error accoured , please trye agin");
            window.location.reload();
        }
        else
            if (result == 0) {
                window.location.replace("/UI/Desktop.aspx");
            }
            else {
                alert("Some unhandle execption happend in the server");
                window.location.reload();
            }

    });
}

//-------------Vibration

function VibrateAction() {
    var interval = 30;
    var duration = 1000;
    var shake = 10;
    var vibrateIndex = 0;
    var selector = $("#form");
    var stopVibration;
    var vibrate;
    vibrate = function () {
        $(selector).stop(true, false).css({
            position: 'relative',
            left: Math.round(Math.random() * shake) - ((shake + 1) / 2) + 'px',
            //top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'});
            top: 0
        });
    }

    stopVibration = function () {
        clearInterval(vibrateIndex);
        $(selector).stop(true, false).css({
            position: 'static',
            left: '0px',
            top: '0px'
        });
    };
    vibrateIndex = setInterval(vibrate, interval);
    setTimeout(stopVibration, duration);
}

//---------------------------- Key board handler

$(document).keypress(function (e) {
    if (e.keyCode == 13) {
        if (regFlag == 0) {
            Login();

        }
        else {
            FinalValidator
        }

    }

});

$(document).keydown(function (e) {
    if (e.keyCode == 13) {
        if (regFlag == 0) {
            Login();

        }
        else {
            FinalValidator();
        }

    }
    if (e.keyCode == 8) {

    }

});


//-------------------------------------------------------------------------Forget Password Part
$("document").ready(function () {
    $("#forgetPassword").click(ForgetPassword);
    $("#cancel").click(CancelRecovery);
    $("#recoverButton").click(Recovery);
});
function ForgetPassword() {
    $("#loginForm").hide(0);
    $(".SignUpArea").hide(0);
    $("#forgetForm").fadeIn(1000);
    $("#recoveryError").hide(0);
}

function CancelRecovery() {
    $("#loginForm").show(1000);
    $(".SignUpArea").show(1000);
    $("#forgetForm").hide(0);
}



function Recovery() {
    var emailFlag = 0;
    emailAddress = $("#forgetEmail").val();
    if (emailAddress != "") {
        var regex = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
        if (regex.test(emailAddress)) {
            $("#forgetEmail").removeClass("NotVarified");
            $("#recoveryError").hide(10);
            emailFlag = 1;
            $("#timer").show(500);
            $.post("UI/AjaxController.ashx", {
                EMAIL: emailAddress,
                ACTION: "RECOVERPASSWORD",
                ACTIONTYPE: "LOGIN"
            }, function (result) {
                $("#timer").hide(500);
                // alert("Ajax Start");
                if (result == 1) {
                    alert("An Email Send to your Mail Box, Please Check it")
                }
                else if(result==-1){

                    $("#forgetEmail").removeClass("Varified");
                    $("#forgetEmail").addClass("NotVarified");
                    $("#recoveryError").show(100);
                    $("#recoveryError").text("This email does not exist in our database");
                }
            });
        }
        else {
            $("#forgetEmail").removeClass("Varified");
            $("#forgetEmail").addClass("NotVarified");
            $("#recoveryError").show(100);
            $("#recoveryError").text("Please enter a valid email address");
        }
    }
}
